//
//  ViewExt.swift
//  covermedia
//
//  Created by travel on 16/7/18.
//  Copyright © 2016年 covermedia. All rights reserved.
//

import UIKit


public extension UIView {
    public var x: CGFloat { return self.frame.origin.x}
    public var y: CGFloat { return self.frame.origin.y}
    public var w: CGFloat { return self.frame.size.width}
    public var h: CGFloat { return self.frame.size.height}
    
    // MARK: addBorder
    public func addBorder (_ width: CGFloat,color: UIColor) {
        self.layer.borderWidth = width
        self.layer.borderColor = color.cgColor
        self.layer.masksToBounds = true
    }
    
    // MARK: CornerRadius
    public func setCornerRadius (_ radius: CGFloat) {
        self.layer.cornerRadius = radius
        self.layer.masksToBounds = true
    }
    
    
    /// 给view添加绘制边框动画
    ///
    /// - parameter lineWidth:   边框宽度
    /// - parameter strokeColor: 边框颜色
    /// - parameter duration:    绘制时间
    /// - parameter startAngle:  开始角度
    /// - parameter clockwise:   是否是顺时针
    /// - parameter inner:       是否在view内部，反之在外部（parent view
    /// - parameter delegate:    绘制动画代理
    public func cm_strokeCircle(_ lineWidth:CGFloat, color:UIColor, duration:TimeInterval = 3, startAngle:CGFloat = 0, clockwise:Bool = true, inner:Bool = true, stop:((Bool, CALayer?) -> (Void))?) {
        let radius = frame.width / 2
        
        let shapeLayer = CAShapeLayer.init()
        shapeLayer.strokeColor = color.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = lineWidth
        let endAngle = clockwise ? startAngle + CGFloat(M_PI * 2) : startAngle - CGFloat(M_PI * 2)
        if let superview = self.superview, !inner {
            shapeLayer.path = UIBezierPath.init(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise).cgPath
            superview.layer.addSublayer(shapeLayer)
        } else {
            shapeLayer.path = UIBezierPath.init(arcCenter: CGPoint.init(x: radius, y: radius), radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise).cgPath
            layer.addSublayer(shapeLayer)
        }
        shapeLayer.strokeStart = 0
        shapeLayer.strokeEnd = 0
        let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
        strokeEndAnimation.duration = duration
        strokeEndAnimation.repeatCount = 1
        strokeEndAnimation.isRemovedOnCompletion = true
        strokeEndAnimation.fromValue = 1
        strokeEndAnimation.toValue = 0
        let delegate = CMViewCAAnimationDelegate()
        delegate.stopAction = stop
        delegate.layer = shapeLayer
        strokeEndAnimation.delegate = delegate
        shapeLayer.add(strokeEndAnimation, forKey: strokeEndAnimation.keyPath)
    }
}

open class CMViewCAAnimationDelegate:NSObject, CAAnimationDelegate {
    public var stopAction:((Bool, CALayer?) -> (Void))?
    public weak var layer:CALayer?
    
    public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        stopAction?(flag, layer)
    }
}


public enum CMViewAnimationType {
    case spring     // 先缩小，在放大（这个用于点赞）
    case springPlus // 同 spring 额外显示 +1 向上飞的效果
}

// MARK: - 动画相关
public extension UIView {
    public func addAnimation(type:CMViewAnimationType, block:@escaping ((Void) -> Void)) {
        let window = UIApplication.shared.keyWindow
        let frame = convert(self.bounds, to: window)
        
        let minScale:CGFloat = 0.5
        let layer = self.layer
        UIView.animate(withDuration: 0.2, animations: { _ in
            layer.transform = CATransform3DMakeScale(minScale, minScale, 1)
            }, completion: { _ in
                block()
                layer.transform = CATransform3DIdentity
                let animation = CAKeyframeAnimation.init(keyPath: "transform")
                animation.values = [
                    CATransform3DMakeScale(minScale, minScale, 1),
                    CATransform3DMakeScale(1.5, 1.5, 1),
                    CATransform3DMakeScale(1, 1, 1),
                    CATransform3DMakeScale(1.2, 1.2, 1),
                    CATransform3DIdentity
                ]
                animation.isRemovedOnCompletion = true
                animation.duration = 0.3
                layer.add(animation, forKey: animation.keyPath)
                
                if type == .springPlus {
                    let heigth = ceil(UIFont.cm_font(.s).lineHeight + 1)
                    let width = heigth * 3
                    let tipFrame = CGRect.init(x: floor(frame.origin.x + frame.size.width/2 - width/2), y: floor(frame.origin.y + frame.size.height/2 - heigth / 2), width: width, height: heigth)
                    let tipLabel = UILabel.init(frame: tipFrame)
                    tipLabel.textColor = UIColor.cm_color(.red)
                    tipLabel.textAlignment = .center
                    tipLabel.font = UIFont.cm_font(.s)
                    tipLabel.text = "+1"
                    tipLabel.sizeToFit()
                    window?.addSubview(tipLabel)
                    UIView.animate(withDuration: 0.3,
                                   animations: { 
                                    tipLabel.frame = tipFrame.offsetBy(dx: 0, dy: -45)
                                    tipLabel.alpha = 0.3
                    }, completion: { (_) in
                         tipLabel.removeFromSuperview()
                    })
                }
        })
        
    }
}
